<template>
    <div>
        <rui-page :defines="defines">
            <div>
                <Row>
                    <Alert>
                        产品附加方案信息
                    </Alert>
                </Row>
                <Form ref="showResultForm" :model="schemeResultForm" :lable-width="50" :rules="rulesSchemeForm">
                    <Row>
                        <Col :xs="24" :md="12" :lg="8" :xl="6" v-if="op!='add'">
                            <FormItem label="方案编号" prop="planNo" :label-width="100">
                                <Input v-model="schemeResultForm.planNo" style="width: 150px" :disabled="readonlyNo" maxlength="32"/>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="12" :lg="8" :xl="6">
                            <FormItem label="方案名称" prop="extrasPlanName" :label-width="100">
                                <Input style="width: 150px" v-model="schemeResultForm.extrasPlanName" :disabled="readonlyName" maxlength="128"/>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="12" :lg="8" :xl="6">
                            <FormItem label="是否选择产品" prop="isProduct" :label-width="100">
                                <Select v-model="schemeResultForm.isProduct" style="width:150px" :disabled="readonlyName" @on-change="changeIsProduct">
                                    <Option v-for="item in isProductList" :value="item.value" :key="item.value" :label="item.title">
                                        {{item.title}}
                                    </Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col :xs="24" :md="12" :lg="8" :xl="6" v-if="schemeResultForm.isProduct=='1'">
                            <FormItem label="附加产品名称" prop="productPlanId" :label-width="100" class="prodName">
                                <Select v-model="schemeResultForm.productPlanId" :disabled="readonlyName"  :placeholder="productName"
                                        style="width: 150px;"  :label-in-value="true"  @on-change="selectProductData">
                                    <Input search enter-button placeholder="搜索" @on-search="onsearch" />
                                    <Option v-for="item in locationData" :value="item.value" :key="item.value" :label="item.label">{{item.label}}</Option>
                                    <Option :value="schemeResultForm.productPlanId" :data-value="schemeResultForm.productPlanId" style="display:none;">{{productName}}</Option>
                                    <Page v-show="locationData.length>0" :page-size="pageData.pageSize" :total="pageData.total" @on-change="changeBasePage" style="text-align: center;" simple />
                                </Select>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <Row style="text-align: center;">
                    <Button @click="save" icon="md-bookmark" type="primary" v-show="op!='view'">保存</Button>
                </Row>
                <br>
                <Row>
                    <Alert>
                        附加方案项目信息
                    </Alert>
                </Row>
                <rui-table
                    :defineId="'defineExtrasProgram'"
                    :columns="showExtrasColumns"
                    :fixedRight="['action']"
                    :showIndex="false"
                    :select="op!='view'"
                    :slots="[{key:'action',slot:'action'}]"
                    @loadDatas="extrasProjectDatas"
                    ref="extrasProgramConfigTable"
                    @on-selection-change="changeSelect"
                >
                    <template slot="toolBar">
                        <Button @click="add" type="primary" icon="md-add" v-show="op!='view'">新增</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('moveup')"  icon="md-arrow-round-up" v-show="op!='view'">上移</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('movedown')"  icon="md-arrow-round-down" v-show="op!='view'">下移</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('movetop')"  icon="md-arrow-round-up" v-show="op!='view'">置顶</Button>
                        <Button type="primary" size="small" @click="moveTemplateAll('moveaend')"  icon="md-arrow-round-down" v-show="op!='view'">置底</Button>
                    </template>
                    <template slot="action" slot-scope="{ row }">
                        <div v-if="op!='view'">
                            <Button type="error" size="small" @click="remove(row)">删除</Button>
                        </div>
                    </template>
                </rui-table>
                <Row>
                    <Alert>
                        附加方案规则信息
                    </Alert>
                </Row>
                <rui-table
                    :defineId="'defineRuleTable'"
                    :fixedRight="['action']"
                    :showIndex="false"
                    :select="false"
                    :slots="[{key:'action',slot:'action'}]"
                    @loadDatas="queryData"
                    :columns="showColumns"
                    ref="showTable"
                >
                    <template slot="toolBar">
                        <Button @click="addRule" icon="md-add" type="primary" v-show="op!='view'">新增</Button>
                    </template>
                    <template slot="action" slot-scope="{ row }">
                        <div v-if="op!='view'">
                            <Button @click="edit(row)" size="small" type="primary">编辑</Button>
                            <Button type="error" size="small" @click="del(row)">删除</Button>
                            <Button @click="ruleConfig(row)" size="small" type="warning">规则配置</Button>
                        </div>
                    </template>
                </rui-table>

                <Modal
                    v-model="isShowRule"
                    :title="ruleTitle"
                    :width="800"
                    :closable="false"
                    :mask-closable="false"
                    @on-ok="saveRule">
                    <rui-form :form-options="ruleFormOptions" :label-width="120" :read-only="false" ref="ruleForm"/>
                    <div slot="footer">
                        <Button size="small" @click="isShowRule = false">取消</Button>
                        <Button type="primary" size="small" :loading="submitLoading" @click="saveRule">保存</Button>
                    </div>
                </Modal>

                <Modal
                    v-model="dataLoad"
                    :title="ruleConfigTitle"
                    :width="1000"
                    :closable="false"
                    :mask-closable="false">
                    <rule-tree v-if="dataLoad" :rule-data="ruleData" :ruleAtoms="ruleAtoms" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario" @saved="returnRuleId" :rule-id="ruleId"/>
                    <div slot="footer">
                        <Button size="small" @click="dataLoad = false">取消</Button>
                    </div>
                </Modal>
                <Row style="text-align: center;">
                    <Button @click="backPage" icon="md-backspace" type="primary">返回</Button>
                </Row>
            </div>
        </rui-page>
        <Modal
            v-model="isShowConfig"
            :title="extrasTitle"
            :width="1000"
            :closable="false"
            :mask-closable="false">
            <extras ref="extras" v-if="isShowConfig" @saveSuccess="parentReceive" @backPageExtras="backPageExtras" :extrasPlanId="extrasPlanId"/>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>
<script>
    import defineTable from "./define/extras-rule-define";
    import defineRuleTable from "./define/extras-rule-table-define";
    import defineExtrasProgram from "./define/project-program-define";
    import ruiRules from '_c/rui-auto/rui-rules/index'
    import {loadRuleDataById} from '_p/basic/api/rule/rule';
    import {queryAtomsByBizType} from "@/projects/basic/api/rule/ruleAtom";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import extras from "./extrasProgramConfigProject.vue";
    import {
        getRuleInfoList,
        delById,
        addRule,
        editRule,
    } from "@/projects/afs-core-business/api/afs-product/product-rule/product-rule-info";
    import {
        saveOrUpdatePlan
    } from "@/projects/afs-core-business/api/afs-product/product/extrasProgram";
    import {
        getExtrasProjectDatas,
        upPlan,
        downPlan,
        getselectProductData,
        getselectProductDataByID,
        deleteById,
        moveTemplateAll
    } from "@/projects/afs-core-business/api/afs-product/product/extrasProgramConfig";

    import {
        getDictDataByType,
        getByTypes
    } from "_p/basic/api/admin/datadic";

    import {saveRuleOut} from '_p/basic/api/rule/rule';
    import {getUri} from "@/libs/tools";

    export default {
        name: "extras-config",
        components: {
            extras,
            ruleTree: ruiRules
        },
        props: {
            //状态
            op:{
                type:String,
                required: true,
                default: 'view'
            },
            //方案ID
            planId:{
                type:String,
            },
            //方案场景
            fitScope:{
                type:String,
                required: true,
                default: '005'
            },
            //表单
            schemeForm:{
                type:Object,
            },
        },
        data() {
            return {

                //只读
                readonlyNo:true,
                //只读
                readonlyName:true,
                //校验
                rulesSchemeForm: {
                    planNo: [{required: true, message: " 不能为空",trigger: "blur"}],
                    extrasPlanName: [{required: true, message: " 不能为空",trigger: "blur"}],
                    isProduct: [{required: true, message: " 不能为空",trigger: "blur"}],
                    productPlanId: [{required: true, message: " 不能为空",trigger: "blur"}],
                },
                schemeResultForm:{
                    status:'0',
                },

                isShowRule: false,//规则输出信息页面展示
                ruleTitle: null,//规则输出信息页面主题

                modalType:0,
                showColumns: [],

                showExtrasColumns:[],

                ruleFormOptions: [
                    {
                        grids: [
                            {defineId: 'defineTable', span: 24, fields: ['ruleName']},
                            {defineId: 'defineTable', span: 24, fields: ['outputInfo']},
                        ]
                    }
                ],

                dataLoad:false,//规则配置页面开关
                ruleConfigTitle: null,//规则配置页面主题
                ruleAtoms:[],//规则原子
                ruleName:'附加贷方案规则配置',
                ruleGroup:'extrasProgramConfig',//规则组
                businessScenario:'businessScenario',//规则编号
                ruleId : null,//规则返回的规则ID
                ruleData:[],//规则数据
                row:{},

                //附加项目查询
                isShowConfig:false,

                //是否选择子产品
                isProductList:[],
                //子产品列表
                locationData:[],
                //子产品分页
                pageData: {
                    pageNumber: 1,
                    pageSize: 5,
                    total: 0,
                    productPlanName:null
                },

                extrasTitle: "新增附加项目",
                submitLoading:false,//按钮控制
                extrasPlanId:null,//附加方案ID

                productName:null,
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineExtrasProgram",
                        fields: defineExtrasProgram
                    },
                    {
                        id: "defineTable",
                        fields: defineTable
                    },
                    {
                        id: "defineRuleTable",
                        fields: defineRuleTable
                    }
                ];
            }
        },
        methods: {
            changeSelect(e) {
                console.info(JSON.stringify(e))
                this.selectList = e;
                this.selectCount = e.length;
            },
            //初始查询
            query(){
                getselectProductData(this.pageData).then(res => {
                    if (res.code === "0000") {
                        this.locationData = res.data.records;
                        this.pageData.total = res.data.total;
                    }
                });
            },
            //查询子产品信息
            querySelectProductData() {
                getselectProductDataByID({productPlanId:this.schemeResultForm.productPlanId}).then(res => {
                    if (res.code === "0000") {
                        this.productName = res.data.productName;
                    }
                });
            },
            //页码变化
            changeBasePage(value){
                this.pageData.pageNumber = value;
                this.query();
            },
            //保存选择的产品
            selectProductData(object) {
                this.productName = object.label;
            },
            //子产品搜索
            onsearch(v){
                this.pageData.productPlanName = v;
                this.query();
            },
            //数据字典
            getDictData(){
                getDictDataByType("whetherStatus").then(res => {
                    if (res.code === "0000") {
                        this.isProductList = res.data;
                    }
                });
            },
            //是否赋值
            changeIsProduct(val){
                console.info("是否赋值的方法："+JSON.stringify(val));
                if(val==0){
                    this.schemeResultForm.productPlanId = null;
                }
            },
            add() {
                this.modalTitle = "选择附加贷项目";
                if (this.op === "new") {
                    this.$Message.warning("请先保存方案！");
                } else {
                    this.isShowConfig = true;
                    this.extrasPlanId = this.schemeResultForm.id;
                }
            },
            save() {
                this.$refs.showResultForm.validate(valid1 => {
                    if(valid1) {
                        let param = this.schemeResultForm;
                        param["fitScope"]=this.fitScope;
                        param["planId"]=this.planId;
                        //风险定价
                        console.info("风险定价数据保存："+JSON.stringify(param));
                        saveOrUpdatePlan(param).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("保存成功！");
                                //编号只读
                                this.readonlyNo = true;
                                this.schemeResultForm = res.data;
                                //返回信息
                                this.$emit('backInfo', res.data);
                            }
                        });
                    }
                });
            },
            parentReceive() {
                console.info("成功回调！");
                this.isShowConfig = false;
                this.refreshextrasProject();
            },
            backPageExtras() {
                this.isShowConfig = false;
            },
            remove(v) {
                deleteById(v.id).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.msg);
                        this.refreshextrasProject();
                    }
                });
            },
            backPage() {
                this.$emit('next', "退回");
            },
            //初始化
            refreshCom(){
                if("view"==this.op){
                    this.readonlyNo = true;
                    this.readonlyName = true;
                    this.showColumns = ['ruleName', 'outputInfo', 'ruleExpress'];
                    this.showExtrasColumns = ['extrasProjectNo','extrasProjectName','isExistsFather'];
                    this.schemeResultForm = this.schemeForm;
                    this.refresh();
                    this.refreshextrasProject();
                    //子产品查询
                    this.query();
                    this.querySelectProductData();
                }
                if("add"==this.op){
                    this.readonlyNo = false;
                    this.readonlyName = false;
                    this.showColumns = ['action', 'ruleName', 'outputInfo', 'ruleExpress'];
                    this.showExtrasColumns = ['extrasProjectNo','extrasProjectName','isExistsFather','action'];
                }
                if("edit"==this.op){
                    this.readonlyNo = true;
                    this.readonlyName = false;
                    this.showColumns = ['action', 'ruleName', 'outputInfo', 'ruleExpress'];
                    this.showExtrasColumns = ['extrasProjectNo','extrasProjectName','isExistsFather','action'];
                    this.schemeResultForm = this.schemeForm;
                    this.refresh();
                    this.refreshextrasProject();
                    //子产品查询
                    this.query();
                    this.querySelectProductData();
                }
            },
            //刷新页面
            refresh() {
                this.$refs['showTable'].reloadData();
            },
            refreshextrasProject() {
                this.$refs['extrasProgramConfigTable'].reloadData();
            },
            extrasProjectDatas( pageNumber, pageSize) {
                let extrasProjectDatas = {pageNumber:pageNumber,pageSize:pageSize};
                extrasProjectDatas["extrasPlanId"] = this.planId;
                getExtrasProjectDatas(extrasProjectDatas).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.extrasProgramConfigTable.updateTableData(records, total);
                    }
                });
            },
            queryData(pageNumber,pageSize) {
                let queryData = {
                    pageNumber:pageNumber,
                    pageSize:pageSize,
                    planId:this.planId,
                    fitScope:this.fitScope,
                };
                getRuleInfoList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.showTable.updateTableData(records, total);
                    }
                });
            },
            addRule() {
                if (this.op === "new") {
                    this.$Message.warning("请先保存方案！");
                } else {
                    this.ruleTitle = "新增规则";
                    this.isShowRule = true;
                    this.modalType = 0;
                    this.$refs.ruleForm.setAllFieldRequired(true);
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFrom();
                    });
                }
            },
            edit(row) {
                this.$refs.ruleForm.resetFrom();
                this.ruleTitle = "编辑规则";
                this.isShowRule = true;
                this.modalType = 1;
                this.$refs.ruleForm.updateFormData(deepClone(row));
                this.$refs.ruleForm.setAllFieldRequired(true);
            },
            ruleConfig(row) {
                this.row = row;
                this.ruleId = row.ruleId;
                this.ruleName=row.ruleName;
                this.businessScenario = row.id;
                this.ruleGroup = row.planId;
                this.ruleConfigTitle = "编辑规则";
                if(row.ruleId!=null){
                    loadRuleDataById(this.ruleId).then(res => {
                        if(res.code='0000'){
                            if(res.data.length>0) {
                                this.ruleData=res.data;
                                this.dataLoad = true;
                            }
                        }
                    });
                }else{
                    this.ruleData = [];
                    this.dataLoad = true;
                }
            },
            del(v) {
                this.$Modal.confirm({
                    title: "确认删除吗",
                    content: "您确认要删除这条规则?",
                    onOk: () => {
                        delById(v.id).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            saveRule() {
                this.$refs.ruleForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            var param = this.$refs.ruleForm.getFormData();
                            param.planId = this.planId;
                            param.fitScope = this.fitScope;
                            this.submitLoading = true;
                            addRule(param).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.refresh();
                                    this.isShowRule = false;
                                }
                            })
                                .catch(() => {
                                    this.submitLoading = false;
                                    this.refresh();
                                });
                        } else {
                            // 编辑
                            this.submitLoading = true;
                            editRule(this.$refs.ruleForm.getFormData()).then(res => {
                                this.submitLoading = false;
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.refresh();
                                    this.isShowRule = false;
                                }
                            })
                                .catch(() => {
                                    this.submitLoading = false;
                                    this.refresh();
                                });
                            if (param.ruleId != null) {
                                this.saveRuleOut(param.ruleId, param.outputInfo);
                            }
                        }
                    }
                });
            },
            returnRuleId(ruleId, expressValue) {
                this.ruleId = ruleId;
                console.log(ruleId);
                this.dataLoad = false;
                // 编辑
                this.row.ruleId = ruleId;
                this.row.ruleExpress = expressValue;
                this.row.activeStatus = "0";
                editRule(this.row)
                    .then(res => {
                        if (res.code === "0000") {
                            this.refresh();
                        }
                    })
                    .catch(() => {
                        this.refresh();
                    });
                this.saveRuleOut(ruleId, this.row.outputInfo);
            },
            saveRuleOut(ruleId, outputInfo) {
                let rule = {
                    "id": ruleId,
                    "ruleOut": outputInfo
                };
                saveRuleOut(rule, getUri('rule')).then(res => {
                    if (res.code === "0000") {
                        this.refresh();
                    }
                }).catch(() => {
                    this.$Message.error("规则输出保存失败！");
                });
            },
            moveTemplateAll(moveType) {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要移动的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认移动吗",
                    content: "您确认要移动所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        this.operationLoading = true;
                        moveTemplateAll({
                            ids: ids,
                            extrasPlanId:this.schemeResultForm.id,
                            moveType:moveType
                        }).then(res => {
                            this.operationLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("移动成功");
                                this.refreshextrasProject();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
        },
        mounted() {
            this.getDictData();
            this.refreshCom();
            queryAtomsByBizType(this.fitScope,'product').then(res => {
                if (res.code === "0000") {
                    this.ruleAtoms = res.data;
                }
            });
        }
    };
</script>
<style>
    .prodName>>>.ivu-select-placeholder{
        color:#515a6e;
    }
</style>
